import jwt
from django.contrib.auth.models import AnonymousUser
from jwt import InvalidTokenError
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import BasePermission

from common.models import User
from zhipin.settings import SECRET_KEY


class BossPermission(BasePermission):

    @staticmethod
    def has_permission(request, view):
        if isinstance(request.user, AnonymousUser):
            return False
        return request.user.is_boss


class LoginRequiredAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_TOKEN')
        if token:
            try:
                payload = jwt.decode(token, SECRET_KEY)
                user = User()
                user.id = payload['userid']
                user.is_boss = payload['isboss']
                user.is_authenticated = True
                return user, token
            except InvalidTokenError:
                pass
        raise AuthenticationFailed('请提供有效的身份令牌')


class CustomizedPagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'size'
    max_page_size = 50
